package com.lingnan.service.impl;

import com.lingnan.feign.NotificationFeignClient;
import com.lingnan.entity.dto.NewMessageRequest;
import com.lingnan.entity.po.ChatSession;
import com.lingnan.entity.po.CompanyHr;
import com.lingnan.entity.po.JobSeeker;
import com.lingnan.entity.po.UserAccount;
import com.lingnan.entity.vo.ChatSessionVO;
import com.lingnan.feign.UserFeignClient;
import com.lingnan.mapper.*;
import com.lingnan.service.ChatSessionService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ChatSessionServiceImpl implements ChatSessionService {

    @Resource
    private ChatSessionMapper sessionMapper;
    @Resource
    private JobSeekerMapper jobSeekerMapper;
    @Resource
    private CompanyHrMapper companyHrMapper;
    @Resource
    private UserAccountMapper userAccountMapper;
    @Resource
    private NotificationFeignClient notificationFeignClient;
    @Resource
    private UserFeignClient userFeignClient;

    @Override
    public List<ChatSession> getUserSessions(Long userId, Integer userType) {
        // 根据用户类型查询对应会话
        if (userType == 0) { // 求职者
            return sessionMapper.selectBySeekerId(userId);
        } else if (userType == 3) { // HR
            return sessionMapper.selectByHrId(userId);
        }
        return List.of();
    }

    @Transactional
    @Override
    public void updateLastMessage(Long sessionId, String lastMsg) {
        sessionMapper.updateLastMessage(sessionId, lastMsg, new Date());
    }

    @Transactional
    @Override
    public void incrementUnreadCount(Long sessionId, Long receiverId, String lastMsg) {
        // 1. 增加未读计数
        Date now = new Date();
        int rows = sessionMapper.incrementUnreadCount(sessionId, receiverId, lastMsg, now);
        log.info("更新会话未读数和最后消息: sessionId={}, receiverId={}, 影响行数={}",
                sessionId, receiverId, rows);

        // 2. 获取会话信息
        ChatSession session = sessionMapper.selectById(sessionId);
        if (session != null) {
            // 3. 解析发送者信息
            log.info("sessionId={}",sessionId);
            Long senderId = resolveSenderId(session, receiverId);
            String senderName = resolveSenderName(session, receiverId);
            String preview = lastMsg.length() > 20 ? lastMsg.substring(0, 20) + "..." : lastMsg;

            // 4. 构造通知请求
            NewMessageRequest request = new NewMessageRequest();
            request.setSenderId(senderId);
            request.setReceiverId(receiverId);
            request.setSenderName(senderName);
            request.setMessagePreview(preview);

            // 5. 发送通知（添加日志和异常处理）
            try {
                log.info("发送新消息通知: receiverId={}, senderName={}", receiverId, senderName);
                notificationFeignClient.sendNewMessageNotification(request);
            } catch (Exception e) {
                log.error("调用通知服务失败", e);
            }
        }
    }

    @Transactional
    @Override
    public void resetUnreadCount(Long sessionId, Long userId) {
        sessionMapper.resetUnreadCount(sessionId, userId);
    }

    private Long resolveSenderId(ChatSession session, Long receiverId) {
        if (session.getSeekerId().equals(receiverId)) {
            return session.getHrId();
        }
        return session.getSeekerId();
    }

    private String resolveSenderName(ChatSession session, Long receiverId) {
        try {
            // 确定对方用户ID
            Long counterpartUserId = resolveSenderId(session, receiverId);

            // 直接通过用户账户ID查询用户信息
            UserAccount account = userFeignClient.getUserAccountById(counterpartUserId);

            // 优先返回昵称，没有则返回用户名
            return account != null ?
                    (account.getNickName() != null ? account.getNickName() : account.getUsername())
                    : "用户" + counterpartUserId;
        } catch (Exception e) {
            log.error("获取用户信息失败: sessionId={}, receiverId={}", session.getId(), receiverId, e);
            return "未知用户";
        }
    }

    @Override
    public List<ChatSessionVO> getUserSessionsVO(Long userId, Integer userType) {
        List<ChatSession> sessions = getUserSessions(userId, userType);
        return sessions.stream().map(session -> {
            ChatSessionVO vo = new ChatSessionVO();
            vo.setId(session.getId());
            vo.setLastMsg(session.getLastMsg());
            vo.setLastMsgTime(session.getLastMsgTime());

            // 根据当前用户类型设置对方信息
            if (userType == 0) { // 当前用户是求职者
                vo.setUnreadCount(session.getSeekerUnreadCount());
                vo.setCounterpartId(session.getHrId());
                vo.setCounterpartName(getCounterpartName(session.getHrId()));
                vo.setCounterpartType(3);
            } else if (userType == 3) { // 当前用户是HR
                vo.setUnreadCount(session.getHrUnreadCount());
                vo.setCounterpartId(session.getSeekerId());
                vo.setCounterpartName(getCounterpartName(session.getSeekerId()));
                vo.setCounterpartType(0);
            }
            return vo;
        }).collect(Collectors.toList());
    }

    private void handleHrCounterpart(ChatSession session, ChatSessionVO vo) {
        // 1. 获取HR信息
        CompanyHr hr = companyHrMapper.selectById(session.getHrId());
        if (hr == null) return;

        // 2. 通过HR获取关联的用户账户
        UserAccount hrAccount = userAccountMapper.selectById(hr.getUserAccountId());

        // 3. 设置对方信息
        vo.setCounterpartName(hrAccount.getNickName() != null ?
                hrAccount.getNickName() : hrAccount.getUsername());
        vo.setCounterpartAvatar(hrAccount.getAvatar());
        vo.setCounterpartType(3); // HR类型
    }

    private void handleSeekerCounterpart(ChatSession session, ChatSessionVO vo) {
        // 1. 获取求职者信息
        JobSeeker seeker = jobSeekerMapper.selectById(session.getSeekerId());
        if (seeker == null) return;

        // 2. 通过求职者获取关联的用户账户
        UserAccount seekerAccount = userAccountMapper.selectById(seeker.getUserId());

        // 3. 设置对方信息
        vo.setCounterpartName(seekerAccount.getNickName() != null ?
                seekerAccount.getNickName() : seekerAccount.getUsername());
        vo.setCounterpartAvatar(seekerAccount.getAvatar());
        vo.setCounterpartType(0); // 求职者类型
    }

    @Override
    public int getSessionUnreadCount(Long sessionId, Long userId) {
        // 1. 查询会话信息
        ChatSession session = sessionMapper.selectById(sessionId);
        if (session == null) {
            return 0;
        }

        // 2. 验证用户是否属于该会话
        if (!session.getSeekerId().equals(userId) && !session.getHrId().equals(userId)) {
            return 0;
        }

        // 3. 通过用户ID查询用户类型
        UserAccount user = userAccountMapper.selectById(userId);
        if (user == null) {
            return 0;
        }

        // 4. 根据用户类型返回对应的未读数
        if (user.getUserType() == 0) { // 求职者
            return session.getSeekerUnreadCount();
        } else if (user.getUserType() == 3) { // HR
            return session.getHrUnreadCount();
        }
        return 0;
    }

    @Override
    public ChatSession getSessionById(Long sessionId) {
        return sessionMapper.selectById(sessionId);
    }

    @Transactional
    public Long createSession(Long seekerId, Long hrId) {
        // 增加会话存在性检查
        ChatSession existing = sessionMapper.findBySeekerIdAndHrId(seekerId, hrId);
        if (existing != null) return existing.getId();

        // 创建新会话（不再设置默认消息）
        ChatSession session = new ChatSession();
        session.setSeekerId(seekerId);
        session.setHrId(hrId);
        session.setSeekerUnreadCount(0);
        session.setHrUnreadCount(0);
        session.setLastMsg(""); // 留空，第一条消息会更新
        session.setLastMsgTime(new Date());

        sessionMapper.insert(session);
        return session.getId();
    }

    @Override
    @Transactional
    public ChatSessionVO createOrGetSession(Long userId, Integer userType, Long targetUserId, Integer targetUserType) {
        Long seekerId, hrId;
        
        // 根据用户类型确定求职者和HR的ID
        if (userType == 0 && targetUserType == 3) { // 求职者 -> HR
            seekerId = userId;
            hrId = targetUserId;
        } else if (userType == 3 && targetUserType == 0) { // HR -> 求职者
            seekerId = targetUserId;
            hrId = userId;
        } else {
            throw new IllegalArgumentException("不支持的用户类型组合");
        }
        
        // 查找或创建会话
        ChatSession existing = sessionMapper.findBySeekerIdAndHrId(seekerId, hrId);
        Long sessionId;
        
        if (existing != null) {
            sessionId = existing.getId();
        } else {
            sessionId = createSession(seekerId, hrId);
            existing = sessionMapper.selectById(sessionId);
        }
        
        // 构造返回的VO
        ChatSessionVO vo = new ChatSessionVO();
        vo.setId(sessionId);
        vo.setLastMsg(existing.getLastMsg());
        vo.setLastMsgTime(existing.getLastMsgTime());
        
        // 设置对方信息和未读数
        if (userType == 0) { // 当前用户是求职者
            vo.setUnreadCount(existing.getSeekerUnreadCount());
            vo.setCounterpartId(hrId);
            vo.setCounterpartName(getCounterpartName(hrId));
            vo.setCounterpartType(3);
        } else { // 当前用户是HR
            vo.setUnreadCount(existing.getHrUnreadCount());
            vo.setCounterpartId(seekerId);
            vo.setCounterpartName(getCounterpartName(seekerId));
            vo.setCounterpartType(0);
        }
        
        return vo;
    }

    private String getCounterpartName(Long userId) {
        try {
            UserAccount account = userFeignClient.getUserAccountById(userId);
            if (account != null) {
                // 优先返回昵称，没有则返回用户名
                return account.getNickName() != null ?
                        account.getNickName() : account.getUsername();
            }
        } catch (Exception e) {
            log.error("获取用户信息失败: userId={}", userId, e);
        }
        return "用户" + userId;
    }
}